package tgc.edu.yzy.Impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import tgc.edu.yzy.bean.OpenLayout;
import tgc.edu.yzy.custom.TimeUtils;
import tgc.edu.yzy.jdbc.OpenLayoutJDBC;
import tgc.edu.yzy.mapper.OpenLayoutMapper;
import tgc.edu.yzy.service.OpenLayoutService;
@Service(value="OpenLayoutService")
public class OpenLayoutImpl{
	@Autowired
	private OpenLayoutMapper dao;
	
	public static Map<String,OpenLayout> openlayoutMap = new HashMap<>(); 
	
	public String updateMap() {
		openlayoutMap = new HashMap<>(); 
		List<OpenLayout> list = OpenLayoutJDBC.list();
		for (OpenLayout openLayout : list) {
			openlayoutMap.put(openLayout.getNumber(), openLayout);
		}
		return "共同步阵型："+openlayoutMap.size()+"个到缓存！openlayoutMap";
	}
	
	
	
	/*public void delete() {
		dao.delete();
	}*/
	/*public String updateQt() {
		String remsg = "";
		String qt[][] = {{"https://shimo.im/docs/Ct3c6VYyGvWxJhcg/read","8本"},{"https://shimo.im/docs/qGKhqyck3Th68ygy/read","9本"}
			,{"https://shimo.im/docs/PJd8D3JghjXhxCG8/read","10本"},{"https://shimo.im/docs/WwgChTtHqXCyJGcP/read","11本"},
			{"https://shimo.im/docs/vQy9kJQQhr9Vq8v8/read","12本"},{"https://shimo.im/docs/v63pPcctJyP9YV3t/read","冲杯"}
			,{"https://shimo.im/docs/xJPvVH6tTGGxPKWd/read","种树"},
			{"https://shimo.im/docs/XYjttXGRCcqTprwG/read","娱乐"},
			{"https://shimo.im/docs/D9VqHCWXr3J3vcHy/read","夜世界"}
		};
		System.out.println(TimeUtils.getStringDate()+" 已删除词库");
		for (int i = 0; i < qt.length; i++) {
			Integer uodate = getUodate(qt[i][0], qt[i][1], 1);
			remsg += "更新"+qt[i][1]+"阵型："+uodate+" 个！\n";
		}
		return remsg;
	}*/
	/*private Integer getUodate(String gouurl, String tb, int sum) {
		String content = "";
		int whilesum = 0;
		while (content == "") {
			try {
				if(whilesum == 30) {
					return -1;
				}
				Map<String, Object> data = new HashMap<String, Object>();
				content = getURLContent(gouurl, data, "GET");
			} catch (Exception e) {
				System.out.println(gouurl+"查询失败");
				whilesum++;
			}
		}
		String substring = content.substring(content.indexOf("ql-divide"), content.indexOf("sc-bdVaJa cEcoPi"));
		String[] split = substring.split("data-src=\\\"");
		for (int i = 0; i < split.length; i++) {
			System.out.println();
			int indexOf = split[i].indexOf("\"/>");
			if (indexOf != -1) {
				System.out.println(i);
				System.out.println(split[i].substring(0, split[i].indexOf("\"/>")));
				if (i > 0) {
					String[] split2 = split[i].split("href=\"http");
					if (split2.length == 2) {
						for (int j = 1; j < split2.length; j++) {
							System.out.println("http" + split2[j].substring(0, split2[j].indexOf("\"")));
							OpenLayout open = new OpenLayout();
							open.setCreateName("晴天阵型");
							open.setCreateDate(TimeUtils.getStringDate());
							open.setImageUrl(split[i].substring(0,split[i].indexOf("\"/>")));
							String nub = "";
							if(sum<10) {
								nub = tb+"阵型00"+sum;
							}else if(sum<100) {
								nub = tb+"阵型0"+sum;
							}else{
								nub = tb+"阵型"+sum;
							}
							open.setNumber(nub);
							open.setRemark("");
							open.setType(tb);
							open.setUrl("http"+split2[j].substring(0,split2[j].indexOf("\"")));
							this.save(open);
							sum ++;
						}
					}
				}
			}

		}

		System.out.println(tb + "已更新完毕，更新" + sum + "条数据！");
		return sum;
	}*/

	public static String getURLContent(String requestUrl, Map<String, Object> data, String method) throws IOException {
		HttpURLConnection conn = null;
		BufferedReader br = null;
		StringBuffer sb = new StringBuffer();
		String content = null;
		// GET请求的url链接
		if (null == method || "GET" == method) {
			requestUrl = requestUrl + "?" + urlEncode(data);
		}

		try {

			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();

			// 设置请求方式
			if ("GET" == method || null == method) {
				conn.setRequestMethod("GET");
			} else {
				conn.setRequestMethod("POST");
				// 使用URL连接输出
				conn.setDoOutput(true);
			}
			// 设置请求内核
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
			conn.setRequestProperty("Cookie",
					"sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2216d670e937a35c-0dcd5beea752e1-11656d4a-2073600-16d670e937b1e4%22%2C%22%24device_id%22%3A%2216d670e937a35c-0dcd5beea752e1-11656d4a-2073600-16d670e937b1e4%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22%22%2C%22%24latest_referrer_host%22%3A%22%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%7D; shimo_gatedlaunch=0; shimo_kong=2; shimo_svc_edit=1654; sensorsdata2015session=%7B%7D; deviceId=333f57ec-4940-4a3c-b01a-61d34d8e9cab; deviceIdGenerateTime=1569635770806; _csrf=JnRJTCDR7jlLn-AYCgmlE0QW; anonymousUser=-2549833152; shimo_sid=s%3A8srVZc7EtPtJXUFWtaxs0yjfsDaYlZGZ.kQ%2BR6ulAWYb0JXivgYgwLM32rMH6ikpp8%2BrZknQOSAE");
			// 设置不使用缓存
			conn.setUseCaches(false);
			// 设置链接超时时间,毫秒为单位
			conn.setConnectTimeout(10000);
			// 设置读取超时时间，毫秒为单位
			conn.setReadTimeout(10000);
			// 设置当前链接是否自动处理重定向。setFollowRedirects设置所有的链接是否自动处理重定向
			conn.setInstanceFollowRedirects(false);
			// 开启链接
			conn.connect();
			// 处理post请求时的参数
			if (null != data && "POST" == method) {
				DataOutputStream out = new DataOutputStream(conn.getOutputStream());
				out.writeBytes(urlEncode(data));
			}
			// 获取字符输入流
			br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String strContent = null;
			while ((strContent = br.readLine()) != null) {
				sb.append(strContent);
			}
			content = sb.toString();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} finally {
			// 关闭流和链接
			if (null != br) {
				br.close();
			}
			if (null != conn) {
				conn.disconnect();
			}
		}

		return content;
	}

	// 将map型转为请求参数型
	public static String urlEncode(Map<String, ?> data) {
		if (data == null) {
			return "";
		} else {
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, ?> i : data.entrySet()) {
				try {
					sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			return sb.toString();
		}
	}
	public OpenLayout getSuiji() {
		return dao.getSuiji();
	}

}
